package us.feng.tinyspring.beans.factory.support;


import us.feng.tinyspring.beans.BeanDefinition;
import us.feng.tinyspring.beans.BeanException;
import us.feng.tinyspring.beans.TypeConverter;
import us.feng.tinyspring.beans.factory.AbstractBeanFactory;
import us.feng.tinyspring.beans.factory.config.RuntimeBeanReference;

public class BeanDefinitionValueResolver {
	private final AbstractBeanFactory beanFactory;
	
	private final String beanName;

	private final BeanDefinition beanDefinition;

	private final TypeConverter typeConverter;
	
	public BeanDefinitionValueResolver(AbstractBeanFactory beanFactory,String beanName,
			BeanDefinition beanDefintion,TypeConverter typeConverter) {
		this.beanFactory=beanFactory;
		this.beanName=beanName;
		this.beanDefinition=beanDefintion;
		this.typeConverter=typeConverter;	
	}
	
	public Object resolveValueIfNecessary(Object argName, Object value) {
		if(value instanceof RuntimeBeanReference ){
			
			Object o=resolveReference(argName, (RuntimeBeanReference)value);
			return o;
		}
		return value;
	}
	
	private Object resolveReference(Object argName, RuntimeBeanReference ref) {
		String refName=ref.getBeanName();
		try {
			Object bean = this.beanFactory.getBean(refName);
			return bean;
		} catch (BeanException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ref;
	}
}
